    //
//  RootViewController.m
//
//  Created by mac on 11-4-12.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "ObjectiveFlickr.h"
#import "JustPhotoItAppDelegate.h"
#import "OAuthEngine.h"
#import "OAuthController.h"

@implementation RootViewController

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self updateUserInterface:nil];
}

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	NSLog(@"load view");
	
//	NSString *user = [[NSUserDefaults standardUserDefaults] objectForKey:kStoredAuthTokenKeyName];
//	if (user == nil) 
//	{
//		[self addLoginView];
//	}
	
	if ([[JustPhotoItAppDelegate sharedDelegate].flickrContext.authToken length]) {
		loginFlickr.enabled = NO;
	}
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(updateUserInterface:) 
												 name:SnapAndRunShouldUpdateAuthInfoNotification object:nil];
	
	UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 200)];
	imgView.image = [UIImage imageNamed:@"flickr.png"];
	
	[self.view addSubview:imgView];
	[imgView release];

}

-(void)addLoginFlickrView {

	loginFlickrView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]];
	loginFlickrView.backgroundColor = [UIColor whiteColor];
	
	UIImage *img = [UIImage imageNamed:@"flickr.png"];
	UIImageView *flickr = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, img.size.width, img.size.height)];
	flickr.image = img;
	[loginFlickrView addSubview:flickr];
	[flickr release];
	
	loginFlickr = [UIButton buttonWithType:UIButtonTypeCustom];
	img = [UIImage imageNamed:@"loginbutton.png"];
	loginFlickr.frame = CGRectMake(86, 200, 128, 128);
	[loginFlickr setImage:img forState:UIControlStateNormal];
	[loginFlickr setImage:img forState:UIControlStateSelected];
	[loginFlickr setTitle:@"登录" forState:UIControlStateNormal];
	[loginFlickr addTarget:self action:@selector(authorizeAction) forControlEvents:UIControlEventTouchUpInside];
	[loginFlickrView addSubview:loginFlickr];
	
	UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(130, 200, 128, 128)];
	label.backgroundColor = [UIColor clearColor];
	label.text = @"登录";
	label.font = [UIFont systemFontOfSize:20];
	[loginFlickrView addSubview:label];
	[label release];
	
	[self.view addSubview:loginFlickrView];
	[loginFlickrView release];
}

-(void)addLoginSinaView {

	loginSinaView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]];
	loginSinaView.backgroundColor = [UIColor whiteColor];
	
	UIImage *img = [UIImage imageNamed:@"flickr.png"];
	UIImageView *flickr = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, img.size.width, img.size.height)];
	flickr.image = img;
	[loginSinaView addSubview:flickr];
	[flickr release];
	
	UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 250, 38)];
	label.backgroundColor = [UIColor clearColor];
	NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"flickrName"];
	label.text = [NSString stringWithFormat:@"%@,你已经登录Flickr",name];
	label.font = [UIFont systemFontOfSize:16];
	[loginSinaView addSubview:label];
	[label release];
	
	UIButton *loginSina = [UIButton buttonWithType:UIButtonTypeCustom];
	img = [UIImage imageNamed:@"sina.png"];
	loginSina.frame = CGRectMake(86, 200, img.size.width, img.size.height);
	[loginSina setImage:img forState:UIControlStateNormal];
	[loginSina setImage:img forState:UIControlStateSelected];
	[loginSina addTarget:self action:@selector(loginToSina) forControlEvents:UIControlEventTouchUpInside];
	[loginSinaView addSubview:loginSina];
	

	
	[self.view addSubview:loginSinaView];
	[loginSinaView release];
}


- (IBAction)authorizeAction
{
	loginFlickr.enabled = NO;
    
    NSURL *loginURL = [[JustPhotoItAppDelegate sharedDelegate].flickrContext loginURLFromFrobDictionary:nil requestedPermission:OFFlickrWritePermission];
    [[UIApplication sharedApplication] openURL:loginURL];
}

-(void)loginToSina {

	if (!_engine){
		_engine = [[OAuthEngine alloc] initOAuthWithDelegate: self];
		_engine.consumerKey = @"4035132033";
		_engine.consumerSecret = @"60f9c3c663c68fce1c7f2da2c9810e9c";
	}
	[self performSelector:@selector(loadTimeline) withObject:nil afterDelay:0.5];
}

- (void)loadTimeline {
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];
	else {
		NSLog(@"Authenicated for %@..", _engine.username);
//		[OAuthEngine setCurrentOAuthEngine:_engine];
//		[self loadData];
		
		/*
		 WeiboClient *followClient = [[WeiboClient alloc] initWithTarget:self 
		 engine:_engine
		 action:@selector(followDidReceive:obj:)];
		 [followClient follow:1727858283]; // follow the author!
		 */ 
	}
}


- (void)updateUserInterface:(NSNotification *)notification
{
	NSLog(@"%s",__FUNCTION__);
	if ([[JustPhotoItAppDelegate sharedDelegate].flickrContext.authToken length]) {	
		if ([loginFlickrView isDescendantOfView:self.view]) {
			[loginFlickrView removeFromSuperview];
		}
		
		if (![[NSUserDefaults standardUserDefaults] objectForKey:@"authData"]) {
			[self addLoginSinaView];
		}
		else if([loginSinaView isDescendantOfView:self.view]){
			[loginSinaView removeFromSuperview];
		}

		
		if ([[JustPhotoItAppDelegate sharedDelegate].flickrUserName length]) {   //首次登录
			NSString *name = [NSString stringWithFormat:@"%@", [JustPhotoItAppDelegate sharedDelegate].flickrUserName];
			[[NSUserDefaults standardUserDefaults] setObject:name forKey:@"flickrName"];
		}
		else { //重复登录
			//authorizeDescriptionLabel.text = @"You've logged in";
			NSLog(@"You've logged in");
		}
		
		//snapPictureButton.enabled = YES;
	}
	else {
		[self addLoginFlickrView];		
		//authorizeDescriptionLabel.text = @"Login to Flickr";		
		//snapPictureButton.enabled = NO;
	}
	
//	if ([self.flickrRequest isRunning]) {
//		[snapPictureButton setTitle:@"Cancel" forState:UIControlStateNormal];
//		[snapPictureButton setTitle:@"Cancel" forState:UIControlStateHighlighted];
//		[snapPictureButton setTitle:@"Cancel" forState:UIControlStateDisabled];
//		authorizeButton.enabled = NO;
//	}
//	else {
//		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//			[snapPictureButton setTitle:@"Snap" forState:UIControlStateNormal];
//			[snapPictureButton setTitle:@"Snap" forState:UIControlStateHighlighted];
//			[snapPictureButton setTitle:@"Snap" forState:UIControlStateDisabled];
//			snapPictureDescriptionLabel.text = @"Use camera";
//		}
//		else {
//			[snapPictureButton setTitle:@"Pick Picture" forState:UIControlStateNormal];
//			[snapPictureButton setTitle:@"Pick Picture" forState:UIControlStateHighlighted];
//			[snapPictureButton setTitle:@"Pick Picture" forState:UIControlStateDisabled];						
//			snapPictureDescriptionLabel.text = @"Pick from library";
//		}
//		
//		authorizeButton.enabled = YES;
//	}
	
}
//- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
//	NSLog(@"%s",__FUNCTION__);
//
//    [scrollView setZoomScale:scale+0.01 animated:NO];
//    [scrollView setZoomScale:scale animated:NO];
//}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -sina weibo delegate

- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username{
	
	NSLog(@"your sina username is : %@",username);
	//[[NSUserDefaults standardUserDefaults] setObject:username forKey:@"sinaName"];
	[loginSinaView removeFromSuperview];
}

//=============================================================================================================================
#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
	NSLog(@"用户名：%@",username);
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername:(NSString *) username{
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}
#pragma mark -view cycle
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
